package top.infopub.mgr.cap.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.cap.dao.CreditBalanceManagementDao;
import top.infopub.mgr.cap.dao.LookInfoBeginBankDao;
import top.infopub.mgr.cap.dao.LookInfoBeginDao;
import top.infopub.mgr.cap.dao.LookInfoDao;
import top.infopub.mgr.cap.domain.FinancingDomain;
import top.infopub.mgr.cap.domain.LookInfoDomain;
import top.infopub.mgr.cap.dto.LookInfoBeginDto;
import top.infopub.mgr.cap.jsonvo.LookInfoBeginJsonVo;
import top.infopub.mgr.cap.service.LookInfoBeginService;
import top.infopub.mgr.cap.vo.LookInfoBeginVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.dao.ProjectInfoDao;
import top.infopub.mgr.mkt.dao.ProjectSubInfoDao;
import top.infopub.mgr.mkt.service.BaseLineService;
import top.infopub.mgr.mkt.vo.BaseLineVo;
import top.infopub.model.cap.CreditBalanceManagement;
import top.infopub.model.cap.LookInfo;
import top.infopub.model.cap.LookInfoBegin;
import top.infopub.model.cap.LookInfoBeginBank;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.model.mkt.ProjectInfo;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
public class LookInfoBeginServiceImpl implements LookInfoBeginService {

    @Autowired
    private LookInfoBeginDao lookinfoBeginDao;

    @Autowired
    private LookInfoBeginBankDao lookInfoBeginBankDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private ProjectSubInfoDao projectSubInfoDao;

    @Autowired
    private BaseLineService baseLineService;

    @Autowired
    private CreditBalanceManagementDao creditBalanceManagementDao;
    @Autowired
    private LookInfoDao lookInfoDao;
    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Override
    public Page<LookInfoDomain> selectByDomainWhere(Page<LookInfoDomain> page, LookInfoBeginVo lookInfoBeginVo) {
        //处理时间范围
        if (!StringUtils.isEmpty(lookInfoBeginVo.getDates())) {
            String[] splitTime = lookInfoBeginVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                lookInfoBeginVo.setEndDate(format.parse(splitTime[1]));
                lookInfoBeginVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<LookInfoDomain>)lookinfoBeginDao.selectByDomainWhere(lookInfoBeginVo);
    }

    @Override
    public LookInfoBegin selectByProCode(String proCode) {
        return lookinfoBeginDao.selectByProCode(proCode);
    }

    @Override
    public Page<FinancingDomain> selectFinByDomainWhere(Page<FinancingDomain> page, LookInfoBeginVo lookInfoBeginVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<FinancingDomain>)lookinfoBeginDao.selectFinByDomainWhere(lookInfoBeginVo);

    }

    @Override
    public LookInfoBeginDto queryDetailById(String id) {

        LookInfoBeginDto lookInfoDto = new LookInfoBeginDto();
        //初调信息
        LookInfoBegin lookInfoBegin = lookinfoBeginDao.selectById(id);
        //详情信息
        lookInfoDto = lookinfoBeginDao.queryDetailById(id);
        //金融机构信息
        List<LookInfoBeginBank> lookInfoBeginBanks = lookInfoBeginBankDao.selectByProCode(lookInfoBegin.getProCode());
        lookInfoDto.setLookInfoBanks(lookInfoBeginBanks);
        //如果初调更改了入库情况 优先取初调
        if (StringUtils.isNotBlank(lookInfoBegin.getIsInStore())){
            lookInfoDto.setIsInStore(lookInfoBegin.getIsInStore());
        }
        //附件
        List<ProjectAttachment> attachmentList = projectAttachmentDao.queryByWhere(lookInfoBegin.getProCode(), ProjectFileTypeEnum.FILE_TYPE45.getCode(), null);
        lookInfoDto.setFileAtt(fileAttaListToArray(attachmentList));
        //查询项目投资组成

        ProjectInfo byProCode = projectInfoDao.findByProCode(lookInfoBegin.getProCode());
        lookInfoDto.setDeviceCost(byProCode.getDeviceCost());
        lookInfoDto.setRowSum(byProCode.getCostCae());
        lookInfoDto.setOtherCost(byProCode.getOtherCost());
        lookInfoDto.setInReadyCost(byProCode.getInReadyCost());
        lookInfoDto.setPeriodInterest(byProCode.getPeriodInterest());
        lookInfoDto.setSumAmount(byProCode.getSumAmount());
//        ProjectSubInfo projectSubInfo = projectSubInfoDao.queryByProCode(lookInfoBegin.getProCode());
//        List<InvestmentInfoVo> investmentInfoVos = JSON.parseArray(projectSubInfo.getContentJson(), InvestmentInfoVo.class);
//        for (InvestmentInfoVo investmentInfoVo : investmentInfoVos) {
//            if (StandardEnum.SHEBEI.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setDeviceCost(investmentInfoVo.getTotal());
//            }else if (StandardEnum.GET_JIANAN.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setRowSum(investmentInfoVo.getTotal());
//            }else if (StandardEnum.GONGCHENG.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setOtherCost(investmentInfoVo.getTotal());
//            }else if (StandardEnum.YUBEI.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setInReadyCost(investmentInfoVo.getTotal());
//            }else if (StandardEnum.JIANSHE.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setPeriodInterest(investmentInfoVo.getTotal());
//            }else if (StandardEnum.HEJI.getBaseLineName().equals(investmentInfoVo.getName())){
//                lookInfoDto.setSumAmount(investmentInfoVo.getTotal());
//            }
//        }
        //底线标准情况
        List<BaseLineVo> baseLineVos = baseLineService.checkIsSatisfy(lookInfoBegin.getProCode());
        lookInfoDto.setBaseLineVos(baseLineVos);
        return lookInfoDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo saveAll(LookInfoBeginJsonVo vo, AuthorizationVO userDtl, List<ProjectAttachment> attachmentList,Integer submitType) {
        //初调信息
        LookInfoBegin lookInfoBegin = new LookInfoBegin();
        BeanUtils.copyProperties(vo.getLookInfoDto(),lookInfoBegin);
        lookInfoBegin.setUptBy(userDtl.getId());
        lookInfoBegin.setUptTime(new Date());
        lookinfoBeginDao.updateById(lookInfoBegin);
        //金融信息
        lookInfoBeginBankDao.deleteByBeginId(lookInfoBegin.getId());
        List<LookInfoBeginBank> lookInfoBanks = vo.getLookInfoBanks();
        for (LookInfoBeginBank lookInfoBank : lookInfoBanks) {
            lookInfoBank.setId(IdFactory.getUUIDUpper());
            lookInfoBank.setLookInfoBeginId(lookInfoBegin.getId());
            lookInfoBank.setProCode(lookInfoBegin.getProCode());
            lookInfoBank.setAddBy(userDtl.getId());
            lookInfoBank.setAddTime(new Date());
        }
        lookInfoBeginBankDao.insertByBatch(lookInfoBanks);
        //附件信息
        if (attachmentList!=null && attachmentList.size()>0){
            //批量插入附件信息
            projectAttachmentDao.deleteByWhere(lookInfoBegin.getProCode(), ProjectFileTypeEnum.FILE_TYPE45.getCode(), null);
            for (ProjectAttachment attachment : attachmentList) {
                attachment.setProCode(lookInfoBegin.getProCode());
            }
            projectAttachmentDao.insertBatch(attachmentList);
        }

        //如果总投资额小于 对接银行的授信额度两家以上 直接到融资尽调
        LookInfo tmpLookInfo = lookInfoDao.queryByProCode(lookInfoBegin.getProCode());
        if (submitType == 1 && tmpLookInfo == null) {
            if (lookInfoBanks.size() >= 2) {
                //查询授信额度
                List<CreditBalanceManagement> balanceManagements = new LinkedList<>();
                for (LookInfoBeginBank lookInfoBank : lookInfoBanks) {
                    CreditBalanceManagement credit = creditBalanceManagementDao.selectByBankName(lookInfoBank.getBankName());
                    balanceManagements.add(credit);
                }
                int count = 0;
                for (CreditBalanceManagement balanceManagement : balanceManagements) {
                    BigDecimal creditLines = new BigDecimal(balanceManagement.getCreditLines());
                    if (vo.getLookInfoDto().getSumAmount().compareTo(creditLines) == -1) { //满足
                        count++;
                    }
                }
                if (count >= 2) { //满足要求到尽调
                    LookInfo lookInfo = new LookInfo();
                    lookInfo.setId(IdFactory.getUUIDUpper());
                    lookInfo.setCodes(IdFactory.getUUIDUpper());
                    lookInfo.setProCode(lookInfoBegin.getProCode());
                    lookInfo.setDebtRate(lookInfoBegin.getDebtRate());
                    lookInfo.setFitNpc(lookInfoBegin.getFitNpc());
                    lookInfo.setAdvise(lookInfoBegin.getAdvise());
                    lookInfo.setAddBy(userDtl.getId());
                    lookInfo.setAddTime(new Date());
                    lookInfo.setUptBy(userDtl.getId());
                    lookInfo.setUptTime(new Date());
                    lookInfo.setIsCredit("0");
                    lookInfo.setImplementationUnit(lookInfoBegin.getImplementationUnit());
                    lookInfo.setConstructionContent(lookInfoBegin.getConstructionContent());
                    lookInfo.setIsInStore(lookInfoBegin.getIsInStore());
                    lookInfoDao.insertById(lookInfo);
                }
            }
        }
        return RspVo.getSuccessResponse();
    }

    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }
}
